<?php
// 应用公共文件

use app\common\service\AuthService;
use think\facade\Cache;

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return url($url, $vars, $suffix, $domain)->build();
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('xdebug')) {

    /**
     * debug调试
     * @param string|array $data 打印信息
     * @param string $type 类型
     * @param string $suffix 文件后缀名
     * @param bool $force
     * @param null $file
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/');
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND);
        $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }
}

if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null $name
     * @return array|mixed
     */
    function sysconfig($group, $name = null)
    {
        $where = ['group' => $group];
//        $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");
//        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $value = \app\admin\model\SystemConfig::where($where)->value('value');
                //Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
            } else {
                $value = \app\admin\model\SystemConfig::where($where)->column('value', 'name');
                //Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
            }
//        }
        return $value;
    }
}

if (!function_exists('array_format_key')) {

    /**
     * 二位数组重新组合数据
     * @param $array
     * @param $key
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }

}

if (!function_exists('auth')) {

    /**
     * auth权限验证
     * @param $node
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {
        $authService = new AuthService(session('admin.id'));
        $check = $authService->checkNode($node);
        return $check;
    }

}

/**
 * 使用curl获取远程数据
 * @param  string $url url连接
 * @return string      获取到的数据
 */
function curl_get_contents($url,$method='GET',$post_data=[]){
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);                //设置访问的url地址
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);               //设置超时
    if($method=='POST'&&!empty($post_data)){
        $post_data_string = http_build_query($post_data);
        curl_setopt($ch, CURLOPT_POST, 1);  // 设置使用post方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string);   //存入转化后的数据字串
    }
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);   //用户访问代理 User-Agent
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch, CURLOPT_REFERER,$_SERVER['HTTP_HOST']);        //设置 referer
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);          //跟踪301
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果
    $r=curl_exec($ch);
    curl_close($ch);
    return $r;
}
function curl_get_contents_temp($url,$method='GET',$post_data=[]){
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);                //设置访问的url地址
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);               //设置超时
    if($method=='POST'&&!empty($post_data)){
        $post_data_string = http_build_query($post_data);
        curl_setopt($ch, CURLOPT_POST, 1);  // 设置使用post方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string);   //存入转化后的数据字串
    }
    //curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);   //用户访问代理 User-Agent
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
    //curl_setopt($ch, CURLOPT_REFERER,$_SERVER['HTTP_HOST']);        //设置 referer
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);          //跟踪301
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果
    $r=curl_exec($ch);
    curl_close($ch);
    return $r;
}
/**
 * 使用curl获取远程数据
 * @param  string $url url连接
 * @return string      获取到的数据
 */
function curl_get_contents_json($url,$method='GET',$post_data=[]){
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);                //设置访问的url地址
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);               //设置超时
    if($method=='POST'&&!empty($post_data)){
        //$post_data_string = http_build_query($post_data);
        $post_data_string = json_encode($post_data);
        curl_setopt($ch, CURLOPT_POST, 1);  // 设置使用post方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string);   //存入转化后的数据字串
    }
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);   //用户访问代理 User-Agent
    //curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        //'Content-Type: application/json; charset=utf-8',
            'Content-Type: application/json',
            'Content-Length: ' . strlen($post_data_string)
    ));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($ch, CURLOPT_REFERER,$_SERVER['HTTP_HOST']);        //设置 referer
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);          //跟踪301
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果
    $r=curl_exec($ch);
    curl_close($ch);
    return $r;
}
function https_request($url,$data,$type){
    if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
        $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
        $data=json_encode($data);
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

//获取汉字的首字母
function getFirstCharters($str)
{
    if (empty($str)) {
        return '';
    }
    //取出参数字符串中的首个字符
    $temp_str = substr($str,0,1);
    if(ord($temp_str) > 127){
        $str = substr($str,0,3);
    }else{
        $str = $temp_str;
        $fchar = ord($str{0});
        if ($fchar >= ord('A') && $fchar <= ord('z')){
            return strtoupper($temp_str);
        }else{
            return null;
        }
    }
    $s1 = iconv('UTF-8', 'gb2312//IGNORE', $str);
    if(empty($s1)){
        return null;
    }
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    if(empty($s2)){
        return null;
    }
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284)
        return 'A';
    if ($asc >= -20283 && $asc <= -19776)
        return 'B';
    if ($asc >= -19775 && $asc <= -19219)
        return 'C';
    if ($asc >= -19218 && $asc <= -18711)
        return 'D';
    if ($asc >= -18710 && $asc <= -18527)
        return 'E';
    if ($asc >= -18526 && $asc <= -18240)
        return 'F';
    if ($asc >= -18239 && $asc <= -17923)
        return 'G';
    if ($asc >= -17922 && $asc <= -17418)
        return 'H';
    if ($asc >= -17417 && $asc <= -16475)
        return 'J';
    if ($asc >= -16474 && $asc <= -16213)
        return 'K';
    if ($asc >= -16212 && $asc <= -15641)
        return 'L';
    if ($asc >= -15640 && $asc <= -15166)
        return 'M';
    if ($asc >= -15165 && $asc <= -14923)
        return 'N';
    if ($asc >= -14922 && $asc <= -14915)
        return 'O';
    if ($asc >= -14914 && $asc <= -14631)
        return 'P';
    if ($asc >= -14630 && $asc <= -14150)
        return 'Q';
    if ($asc >= -14149 && $asc <= -14091)
        return 'R';
    if ($asc >= -14090 && $asc <= -13319)
        return 'S';
    if ($asc >= -13318 && $asc <= -12839)
        return 'T';
    if ($asc >= -12838 && $asc <= -12557)
        return 'W';
    if ($asc >= -12556 && $asc <= -11848)
        return 'X';
    if ($asc >= -11847 && $asc <= -11056)
        return 'Y';
    if ($asc >= -11055 && $asc <= -10247)
        return 'Z';
    return rare_words($asc);
}
//百家姓中的生僻字
function rare_words($asc=''){
    $rare_arr = array(
        -3652=>array('word'=>"窦",'first_char'=>'D'),
        -8503=>array('word'=>"奚",'first_char'=>'X'),
        -9286=>array('word'=>"酆",'first_char'=>'F'),
        -7761=>array('word'=>"岑",'first_char'=>'C'),
        -5128=>array('word'=>"滕",'first_char'=>'T'),
        -9479=>array('word'=>"邬",'first_char'=>'W'),
        -5456=>array('word'=>"臧",'first_char'=>'Z'),
        -7223=>array('word'=>"闵",'first_char'=>'M'),
        -2877=>array('word'=>"裘",'first_char'=>'Q'),
        -6191=>array('word'=>"缪",'first_char'=>'M'),
        -5414=>array('word'=>"贲",'first_char'=>'B'),
        -4102=>array('word'=>"嵇",'first_char'=>'J'),
        -8969=>array('word'=>"荀",'first_char'=>'X'),
        -4938=>array('word'=>"於",'first_char'=>'Y'),
        -9017=>array('word'=>"芮",'first_char'=>'R'),
        -2848=>array('word'=>"羿",'first_char'=>'Y'),
        -9477=>array('word'=>"邴",'first_char'=>'B'),
        -9485=>array('word'=>"隗",'first_char'=>'K'),
        -6731=>array('word'=>"宓",'first_char'=>'M'),
        -9299=>array('word'=>"郗",'first_char'=>'X'),
        -5905=>array('word'=>"栾",'first_char'=>'L'),
        -4393=>array('word'=>"钭",'first_char'=>'T'),
        -9300=>array('word'=>"郜",'first_char'=>'G'),
        -8706=>array('word'=>"蔺",'first_char'=>'L'),
        -3613=>array('word'=>"胥",'first_char'=>'X'),
        -8777=>array('word'=>"莘",'first_char'=>'S'),
        -6708=>array('word'=>"逄",'first_char'=>'P'),
        -9302=>array('word'=>"郦",'first_char'=>'L'),
        -5965=>array('word'=>"璩",'first_char'=>'Q'),
        -6745=>array('word'=>"濮",'first_char'=>'P'),
        -4888=>array('word'=>"扈",'first_char'=>'H'),
        -9309=>array('word'=>"郏",'first_char'=>'J'),
        -5428=>array('word'=>"晏",'first_char'=>'Y'),
        -2849=>array('word'=>"暨",'first_char'=>'J'),
        -7206=>array('word'=>"阙",'first_char'=>'Q'),
        -4945=>array('word'=>"殳",'first_char'=>'S'),
        -9753=>array('word'=>"夔",'first_char'=>'K'),
        -10041=>array('word'=>"厍",'first_char'=>'S'),
        -5429=>array('word'=>"晁",'first_char'=>'C'),
        -2396=>array('word'=>"訾",'first_char'=>'Z'),
        -7205=>array('word'=>"阚",'first_char'=>'K'),
        -10049=>array('word'=>"乜",'first_char'=>'N'),
        -10015=>array('word'=>"蒯",'first_char'=>'K'),
        -3133=>array('word'=>"竺",'first_char'=>'Z'),
        -6698=>array('word'=>"逯",'first_char'=>'L'),
        -9799=>array('word'=>"俟",'first_char'=>'Q'),
        -6749=>array('word'=>"澹",'first_char'=>'T'),
        -7220=>array('word'=>"闾",'first_char'=>'L'),
        -10047=>array('word'=>"亓",'first_char'=>'Q'),
        -10005=>array('word'=>"仉",'first_char'=>'Z'),
        -3417=>array('word'=>"颛",'first_char'=>'Z'),
        -6431=>array('word'=>"驷",'first_char'=>'S'),
        -7226=>array('word'=>"闫",'first_char'=>'Y'),
        -9293=>array('word'=>"鄢",'first_char'=>'Y'),
        -6205=>array('word'=>"缑",'first_char'=>'G'),
        -9764=>array('word'=>"佘",'first_char'=>'S'),
        -9818=>array('word'=>"佴",'first_char'=>'N'),
        -9509=>array('word'=>"谯",'first_char'=>'Q'),
        -3122=>array('word'=>"笪",'first_char'=>'D'),
        -9823=>array('word'=>"佟",'first_char'=>'T'),
    );
    if(array_key_exists($asc, $rare_arr) && $rare_arr[$asc]['first_char']){
        return $rare_arr[$asc]['first_char'] ;
    }else{
        return null;
    }
}
/*
 * 生成随机字符串
 * @param int $length 生成随机字符串的长度
 * @param string $char 组成随机字符串的字符串
 * @return string $string 生成的随机字符串
 */
function str_rand($length = 10, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    if(!is_int($length) || $length < 0) {
        return false;
    }

    $string = '';
    for($i = $length; $i > 0; $i--) {
        $string .= $char[mt_rand(0, strlen($char) - 1)];
    }

    return $string;
}
function str_rand1(){
    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

if (!function_exists('filterEmoji')) {

    // 过滤掉emoji表情
    function filterEmoji($str)
    {
        $str = preg_replace_callback(    //执行一个正则表达式搜索并且使用一个回调进行替换
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }
}